<template>
  <div class="topbar">
    <div class="wrap topbarWrap">
      <div class="l">欢迎来到叩丁狼积分商城</div>
      <ul class="r">
        <li>
          <img class="avatar" :src="headImg" width="26" alt="" />
          用户名：{{ nickName }}
        </li>
        <li>我的鸡腿:{{ coin }}</li>
        <li>获取鸡腿</li>
        <li>叩丁狼官网</li>
        <li class="login-btn" @click="changeloginshow(true)" v-if="!shopshow">
          登录
        </li>
        <li class="cart-btn" v-else @click="shop">
          <img src="../assets/img/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { getuserapi } from "@/request/api";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      // cartTotal: 0,
      // nickName: "--",
      // headImg: require("../assets/img/userImg.f8bbec5e.png"),
      // coin: 0,
    };
  },
  computed: {
    ...mapState(["shopshow"]),
    ...mapState({
      // 自定属性名: (state)=>state.user.xxxx
      nickName: (state) => state.user.nickName,
      headImg: (state) => state.user.headImg,
      coin: (state) => state.user.coin,
      cartTotal: (state) => state.user.cartTotal,
    }),
  },
  methods: {
    updateUserInfo() {
      if (!localStorage.getItem("token")) {
        // !this.shopshow
        return;
        // 不请求，如果状态没变
      }
      getuserapi().then((res) => {
        if (res.code === 0) {
          // console.log(res.data);
          this.updateUser({
            ...res.data.userInfo,
            cartTotal: res.data.cartTotal,
          });
        }
      });
    },
    ...mapMutations(["changeshopshow", "changeloginshow"]),
    ...mapMutations({
      updateUser: "user/updateUserInfo",
    }),
    shop() {
      this.$router.push("/user/Cart");
    },
  },
  created() {
    this.updateUserInfo();
  },
};
</script>
<style lang="less" scoped>
.topbar {
  height: 40px;
  line-height: 40px;
  background: #242b39;
  font-size: 14px;
  .topbarWrap {
    color: #fffefe;
    display: flex;
    justify-content: space-between;
    .r {
      li {
        float: left;
        margin-left: 20px;
        text-align: center;
        cursor: pointer;
        &.login-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
        }
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
      }
      .avatar {
        vertical-align: middle;
        border-radius: 50%;
      }
    }
  }
}
</style>